<template>
  <div class="components-container">
    <aside>
       暂不支持
    </aside>
  </div>
</template>
<script>
import path from 'path'
import { getRoles } from '@/api/role'
import { getUserList, addUser, deleteUser, updateUserRole } from '@/api/user'

const defaultRole = {
  key: '',
  name: '',
  description: '',
  routes: []
}

export default {
  name: 'Price',
  data() {
    return {
      role: Object.assign({}, defaultRole),
      roleData: [],
      userList: [],
      dialogVisible: false,
      dialogType: 'new',
      checkStrictly: false,
      defaultProps: {
        children: '',
        label: 'name'
      },
      checkedRole: [],
      scopeUser: {},
      multipleSelection: [],
      isChangePassword: true,
      isAddModel: false
    }
  },
  computed: {
    routesData() {
      return this.routes
    }
  },
  created() {
    this.getUsers()
    this.getRoles()
  },
  methods: {
    filterRole() {
      const res = []
      this.roleData.forEach(role => {
        if (this.scopeUser.roleIdList.includes(role.id)) {
          res.push(role)
        }
      })
      return res
    },
    filterRole2(list, ids) {
      const res = []
      for (let i = 0; i < list.length; i++) {
        if (ids.includes(list[i].id)) {
          res.push(list[i])
        }
      }
      return res
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row, true)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange(val) {
      console.log(val)
      this.multipleSelection = val
    },
    async getRoles() {
      const res = await getRoles()
      this.roleData = res.data
    },
    async getUsers() {
      const param = {
        pageNO: 1,
        pageSize: 100
      }
      const { data } = await getUserList(param)
      this.userList = data.records
      console.log(data.records)
    },

    // Reshape the routes structure so that it looks the same as the sidebar
    generateRoutes(routes, basePath = '/') {
      const res = []

      for (let route of routes) {
        // skip some route
        if (route.hidden) {
          continue
        }

        const onlyOneShowingChild = this.onlyOneShowingChild(route.children, route)

        if (route.children && onlyOneShowingChild && !route.alwaysShow) {
          route = onlyOneShowingChild
        }

        const data = {
          path: path.resolve(basePath, route.path),
          title: route.meta && route.meta.title

        }

        // recursive child routes
        if (route.children) {
          data.children = this.generateRoutes(route.children, data.path)
        }
        res.push(data)
      }
      return res
    },
    generateArr(routes) {
      let data = []
      routes.forEach(route => {
        data.push(route)
        if (route.children) {
          const temp = this.generateArr(route.children)
          if (temp.length > 0) {
            data = [...data, ...temp]
          }
        }
      })
      return data
    },
    handleAddUser() {
      this.isChangePassword = false
      this.isAddModel = true
      this.scopeUser = {}
      const that = this
      setTimeout(function() {
        that.toggleSelection()
      }, 100)
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    handleEdit(scope) {
      this.isChangePassword = true
      this.isAddModel = false
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.checkStrictly = true
      this.scopeUser = scope.row
      const that = this
      const checked = this.filterRole()
      this.filterRole()
      setTimeout(function() {
        that.toggleSelection(checked)
      }, 100)
    },
    handleDelete({ $index, row }) {
      this.$confirm('确认要删除这个用户吗?', 'Warning', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const data = {
            username: row.username
          }
          await deleteUser(data)
          this.userList.splice($index, 1)
          this.$message({
            type: 'success',
            message: 'Delete succeed!'
          })
        })
        .catch(err => {
          console.error(err)
        })
    },
    generateTree(routes, basePath = '/', checkedKeys) {
      const res = []

      for (const route of routes) {
        const routePath = path.resolve(basePath, route.path)

        // recursive child routes
        if (route.children) {
          route.children = this.generateTree(route.children, routePath, checkedKeys)
        }

        if (checkedKeys.includes(routePath) || (route.children && route.children.length >= 1)) {
          res.push(route)
        }
      }
      return res
    },
    async confirmUser() {
      const isEdit = this.dialogType === 'edit'
      const roleIdList = []
      this.multipleSelection.forEach(e => {
        roleIdList.push(e.id)
      })

      if (isEdit) {
        const data = {
          username: this.scopeUser.username,
          nickname: this.scopeUser.nickname,
          password: this.scopeUser.password,
          isChangePassword: !this.isChangePassword,
          roleIdList: roleIdList
        }
        await updateUserRole(data)
        await this.getUsers()
        // for (let index = 0; index < this.userList.length; index++) {
        //   if (this.userList[index].id === this.scopeUser.id) {
        //     this.userList.splice(index, 1, Object.assign({}, this.scopeUser))
        //     break
        //   }
        // }
      } else {
        const param = {
          username: this.scopeUser.username,
          password: this.scopeUser.password,
          nickname: this.scopeUser.nickname
        }
        const { data } = await addUser(param)
        this.scopeUser.id = data.id
        this.userList.push(data)
      }

      const { id, username } = this.scopeUser
      this.dialogVisible = false
      this.$notify({
        title: 'Success',
        dangerouslyUseHTMLString: true,
        message: `
            <div>用户ID: ${id}</div>
            <div>角色名: ${username}</div>
          `,
        type: 'success'
      })
    },
    // reference: src/view/layout/components/Sidebar/SidebarItem.vue
    onlyOneShowingChild(children = [], parent) {
      let onlyOneChild = null
      const showingChildren = children.filter(item => !item.hidden)

      // When there is only one child route, the child route is displayed by default
      if (showingChildren.length === 1) {
        onlyOneChild = showingChildren[0]
        onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path)
        return onlyOneChild
      }

      // Show parent if there are no child route to display
      if (showingChildren.length === 0) {
        onlyOneChild = { ...parent, path: '', noShowingChildren: true }
        return onlyOneChild
      }

      return false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }

  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
